import 'package:flutter/material.dart';

class FocusImageDemo extends StatelessWidget {
  const FocusImageDemo({super.key});
  static String routeName = 'msic/focus_image';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Focus Image')),
      body: Grid(),
    );
  }
}

class Grid extends StatelessWidget {
  const Grid({super.key});

  @override
  Widget build(BuildContext context) {
    // TODO：官方代码中在外面套了一层Scaffold，不知为何
    return GridView.builder(
      itemCount: 40,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 4,
      ),
      itemBuilder: (context, index) {
        /*return index >= 20
            ? SmallCard(imageAssetName: 'assets/eat_cape_town_sm.jpg')
            : SmallCard(imageAssetName: 'assets/eat_new_orleans_sm.jpg');*/
        String imageAssetName = index >= 20
            ? 'assets/eat_cape_town_sm.jpg'
            : 'assets/eat_new_orleans_sm.jpg';
        return SmallCard(imageAssetName: imageAssetName);
      },
    );
  }
}

class SmallCard extends StatelessWidget {
  const SmallCard({super.key, required this.imageAssetName});
  final String imageAssetName;

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Material(
        child: InkWell(
          onTap: () {
            var nav = Navigator.of(context);
            nav.push<void>(_createRoute(context, imageAssetName));
          },
          child: Image.asset(imageAssetName, fit: BoxFit.cover),
        ),
      ),
    );
  }
}

Route _createRoute(BuildContext parentContext, String image) {
  return PageRouteBuilder(
    pageBuilder: (context, animation, secondaryAnimation) {
      return _SecondPage(image);
    },
    transitionsBuilder: (context, animation, secondaryAnimation, child) {
      var rectAnimation = _createTween(
        parentContext,
      ).chain(CurveTween(curve: Curves.ease)).animate(animation);
      return Stack(
        children: [PositionedTransition(rect: rectAnimation, child: child)],
      );
    },
  );
}

Tween<RelativeRect> _createTween(BuildContext context) {
  var windowSize = MediaQuery.of(context).size;
  var box = context.findRenderObject() as RenderBox;
  var rect = box.localToGlobal(Offset.zero) & box.size;
  var relativeRect = RelativeRect.fromSize(rect, windowSize);

  return RelativeRectTween(begin: relativeRect, end: RelativeRect.fill);
}

class _SecondPage extends StatelessWidget {
  const _SecondPage(this.imageAssetName);
  final String imageAssetName;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Center(
        child: Material(
          child: InkWell(
            onTap: () => Navigator.of(context).pop(),
            child: AspectRatio(
              aspectRatio: 1,
              child: Image.asset(imageAssetName, fit: BoxFit.cover),
            ),
          ),
        ),
      ),
    );
  }
}
